package com.yonyou.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.openapi.base.exception.BusinessException;
import com.yonyou.openapi.base.properties.OpenApiProperties;
import com.yonyou.openapi.base.utils.HttpUtils;
import com.yonyou.openapi.service.SSOToYSIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/yonbip/sso")
public class SSOController {

    @Resource
    SSOToYSIndexService ssoToYSIndexService;
    @Resource
    public OpenApiProperties properties;

    /**
     * 获取单点登录地址
     * 地址示例   http://localhost:8998/yonbip/sso?userId=200043
     */
    @ResponseBody
    @PostMapping
    public String getSSOUrl(@RequestBody String Json) {
        Map<String, String> requestMap = (Map) JSONObject.parseObject(Json, HashMap.class);
        if (null == requestMap.get("userId") || null == requestMap.get("type")) {
            return "单点登录地址获取异常，参数userId或type为空";
        }
        String userId = requestMap.get("userId");
        String type = requestMap.get("type");
        Map<String, String> resMap = new HashMap<>();
        resMap.put("code", "200");
        resMap.put("msg", "单点登录地址获取成功");
        try {
            //pc端拼接跳转地址前部分，OA系统去拼接
            resMap.put("pcurl", ssoToYSIndexService.getRedirectUrl(userId, type));
            //app端拼接跳转地址前部分，OA系统去拼接
            resMap.put("appurl", ssoToYSIndexService.getSSOUrl(userId, type));
        } catch (Exception e) {
            resMap.clear();
            resMap.put("code", "err");
            resMap.put("msg", "单点登录地址获取异常" + e.getMessage());
        }
        log.info("最终单点登录地址:" + JSONObject.toJSONString(resMap));
        return JSONObject.toJSONString(resMap);
    }

}
